package com.glory.dgcpcpda.activity.mfg;

import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.PackageBinListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.PackageEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

public class PackageDownActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvCircuitName)
    TextView tvCircuitName;
    @BindView(R.id.tvCustomCode)
    TextView tvCustomCode;
    @BindView(R.id.tvPackageFrom)
    TextView tvPackageFrom;
    @BindView(R.id.tvStates)
    TextView tvStates;
    @BindView(R.id.tvGoodsNum)
    TextView tvGoodsNum;
    @BindView(R.id.etTrackOutNum)
    EditText etTrackOutNum;
    @BindView(R.id.rvSpiltLotList)
    RecyclerView rvSpiltLotList;
    @BindView(R.id.llTitleLayout)
    LinearLayout llTitleLayout;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotQTY)
    TextView tvLotQTY;
    @BindView(R.id.tvGrade)
    TextView tvGrade;
    @BindView(R.id.tvPackageQTY)
    TextView tvPackageQTY;
    @BindView(R.id.cbReel)
    CheckBox cbReel;
    @BindView(R.id.cbSample)
    CheckBox cbSample;
    private int mMaxReelQTY;
    private int mPackageQTY;
    private PackageBinListAdapter mAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_package_down;
    }

    @Override
    protected void initView() {
        tvTitle.setText("包装卷盘下架");
        llTitleLayout.setVisibility(View.VISIBLE);
        rvSpiltLotList.setVisibility(View.VISIBLE);
        cbReel.setVisibility(View.GONE);
        initRecyclerView(rvSpiltLotList,this);
        mAdapter = new PackageBinListAdapter(null);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(false);
        rvSpiltLotList.setAdapter(mAdapter);
        setMainLayout(llMain);

        initEdit(etLot, s -> LotUtils.searchLotInfo(PackageDownActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                tvCircuitName.setText(response.getPRODUCTMODEL());
                tvCustomCode.setText(response.getLOT().getCUSTOMERCODE());
                tvPackageFrom.setText(response.getLOT().getMAINMATTYPE());
                tvStates.setText(response.getLOT().getSTATE());
                tvLotQTY.setText(response.getLOT().getMAINQTY());
                requestData(s);
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t, "LOTQUERY");
            }
        }));
    }

    private void requestData(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<PackageEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<PackageEntity>>
                (new TypeToken<BaseResponseBean<PackageEntity>>() {
                }.getType(), getSupportFragmentManager(), PackageDownActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PackageEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    mMaxReelQTY = response.body().getResponse().getBody().getMAXREELQTY();
                    etTrackOutNum.setText(String.valueOf(mMaxReelQTY));
                    mPackageQTY = response.body().getResponse().getBody().getPACKAGEQTY();
                    tvPackageQTY.setText(String.valueOf(mPackageQTY));
                    tvGrade.setText(response.body().getResponse().getBody().getBINGRADE());
                    mAdapter.getSelectorData().clear();
                    mAdapter.setNewData(response.body().getResponse().getBody().getXPACKAGEDETAILS());
                    String sampleinfo = response.body().getResponse().getBody().getSAMPLEINFO();
                    String warmingInfo=response.body().getResponse().getBody().getWARNINGINFO();
                    if(warmingInfo!=null&&!warmingInfo.equals("")){
                        showConfirmDialog(warmingInfo);
                    }
                    if (!sampleinfo.equals("")){
                        showConfirmDialog(sampleinfo);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PackageEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PACKAGEUPSHELF");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "UNBINDSELECT");
        map.addProperty("LOTID", s);
        NetUtils.requestPostNet("CPC.PACKAGEUPSHELF", "PACKAGEUPSHELF", PackageDownActivity.this, map, callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit,R.id.cbReel})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvBaseSubmit) {
            if (actionControl("Submit16")) {
                return;
            }

            if (getText(etLot).equals("") || getText(etTrackOutNum).equals("")) {
                showToast("批次号或出站盘数不能为空", false);
                return;
            }

            if (Integer.parseInt(getText(etTrackOutNum)) > (tvPackageQTY.getText().toString().isEmpty() ? 0 : Integer.parseInt(tvPackageQTY.getText().toString()))){
                showToast("出站盘数不能大于最大盘数",false);
                return;
            }

            if (mAdapter.getData().size() > 0 && Integer.parseInt(getText(etTrackOutNum)) < mAdapter.getSelectorData().size()) {
                showToast("出站盘数不能小于勾选数量",false);
                return;

            }

            if (Integer.parseInt(getText(etTrackOutNum)) == (tvPackageQTY.getText().toString().isEmpty() ? 0 : Integer.parseInt(tvPackageQTY.getText().toString()))
                    && mAdapter.getData().size() != mAdapter.getSelectorData().size())   {
                showToast("最大盘数 = 下架盘数  必须全部勾选",false);
                return;
            }


//            if (Integer.parseInt(getText(etTrackOutNum)) + mAdapter.getData().size() > (tvPackageQTY.getText().toString().isEmpty() ? 0 : Integer.parseInt(tvPackageQTY.getText().toString()))){
//                showToast("出站盘数 + 列表条数 > 货架盘数   不允许提交",false);
//                return;
//            }

            if (mAdapter.getData().size() > 0 && mAdapter.getSelectorData().size() <= 0){
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "当前货架有尾数，你确定不下架尾数吗？", new FreeUI_CommonCallback() {
                    @Override
                    public void onSuccess() {
                        submit();
                    }
                }, () -> {}).show(getSupportFragmentManager(),"CONFIRM_DIALOG");
            }else {
                submit();
            }


        }
    }

    private void submit() {
        try {

            if (Integer.parseInt(getText(etTrackOutNum)) != mMaxReelQTY) {
                if (Integer.parseInt(getText(etTrackOutNum)) > mPackageQTY){
                    showToast("出站盘数不能大于总盘数", false);
                    return;
                }
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "与系统推荐的盘数不符，剩余数量：" + (mPackageQTY - Integer.parseInt(getText(etTrackOutNum))) + "盘。是否确认下架?", new FreeUI_CommonCallback() {
                    @Override
                    public void onSuccess() {
                        packageDown();
                    }
                }, () -> {}).show(getSupportFragmentManager(),"SUBMIT_DIALOG");
            }else {
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "剩余数量:" + (mPackageQTY - Integer.parseInt(getText(etTrackOutNum))) + "盘。是否确认下架？", new FreeUI_CommonCallback() {
                    @Override
                    public void onSuccess() {
                        packageDown();
                    }
                }, () -> {}).show(getSupportFragmentManager(),"SUBMIT_DIALOG");
            }
        } catch (NumberFormatException e) {
            showToast("请输入数字", false);
        }
    }

    private void clear() {
        etLot.setText("");
        tvCircuitName.setText("");
        tvCustomCode.setText("");
        tvPackageFrom.setText("");
        tvStates.setText("");
        tvLotQTY.setText("");
        etTrackOutNum.setText("");
        etLot.requestFocus();
        mAdapter.getData().clear();
        mAdapter.getSelectorData().clear();
        mAdapter.notifyDataSetChanged();
    }

    private void packageDown(){
        FreeUI_EntityCallBack<BaseResponseBean<PackageEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<PackageEntity>>
                (new TypeToken<BaseResponseBean<PackageEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PackageEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    PackageEntity body = response.body().getResponse().getBody();
                    showConfirmDialog(body.getSAMPLEINFO().equals("") ? "下架成功" : body.getSAMPLEINFO());
                    clear();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PackageEntity>> response) {
                super.onError(response);
               loadError(response.getException(),"PACKAGEUPSHELF");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "UNBIND");
        map.addProperty("LOTID",getText(etLot));
        map.addProperty("CONSUMEQTY",getText(etTrackOutNum));
//        map.addProperty("ISENDFLAG", cbReel.isChecked() ? "Y" : "N");
        map.add("XPACKAGEDETAILS", new JsonParser().parse(new Gson().toJson(mAdapter.getSelectorData())).getAsJsonArray());
        NetUtils.requestPostNet("CPC.PACKAGEUPSHELF","PACKAGEUPSHELF",this,map,callBack);
    }
}
